<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>ip管理</el-breadcrumb-item>
      <el-breadcrumb-item>网段管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-form :inline="true" :model="addNetworkForm" :rules="addNetworkFormRules" ref="addNetworkFormRef" size="small">
        <el-form-item label="网络地址" prop="segment">
          <el-input v-model="addNetworkForm.segment" placeholder="eg 192.168.6.0"></el-input>
        </el-form-item>
        <el-form-item label="子网掩码" prop="mask">
          <el-input v-model="addNetworkForm.mask" placeholder="eg 255.255.255.0"></el-input>
        </el-form-item>
        <el-form-item label="网关" prop="gateway">
          <el-input v-model="addNetworkForm.gateway" placeholder="192.168.6.1"></el-input>
        </el-form-item>
        <el-form-item label="使用群体" prop="usergroups">
          <el-input v-model="addNetworkForm.usergroups" placeholder="财务部"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addNetwork">添加</el-button>
          <el-button type="warning" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <el-table :data="segmentListData" border stripe style="width: 100%" size="mini">
        <el-table-column prop="segment" label="网络地址" width="115" align="center"></el-table-column>
        <el-table-column prop="mask" label="掩码" width="115" align="center"></el-table-column>
        <el-table-column prop="gateway" label="网关" width="115" align="center"></el-table-column>
        <el-table-column prop="usergroups" label="使用群体" width="115" align="center"></el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="160" align="center">
          <template slot-scope="scope">{{ scope.row.create_time ? scope.row.create_time.substr(0, 19).replace('T', ' ') : '' }} </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button class="tableRowButton" @click="editIp(scope.row)" type="primary" size="mini">编辑</el-button>
            <el-popover placement="top" width="80" :ref="`popover-${scope.$index}`">
              <p>删除网段会同时删除网段内所有ip地址，确定要删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="cancelAction(scope)">取消</el-button>
                <el-button type="primary" @click="deleteSeg(scope)" size="mini">确定</el-button>
              </div>
              <el-button slot="reference" type="danger" size="mini">删除</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="addNetworkForm.pagenum"
        :page-sizes="[10, 20, 50]"
        :page-size="addNetworkForm.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog title="编辑信息" :visible.sync="dialogIpEditFormVisible">
      <el-form :model="ipEditForm" size="small" label-width="50px" label-position="right">
        <el-form-item label="ip">
          <el-input v-model="ipEditForm.ip" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="mac">
          <el-input v-model="ipEditForm.mac" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户">
          <el-input v-model="ipEditForm.user" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="设备">
          <el-input v-model="ipEditForm.equipment" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="ipEditForm.remarks" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editSaveIp" size="small">保 存</el-button>
        <el-button @click="dialogIpEditFormVisible = false" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      addNetworkForm: {
        segment: '',
        mask: '',
        gateway: '',
        usergroups: '',
        pagenum: 1,
        pagesize: 10
      },
      addNetworkFormRules: {
        segment: [
          { max: 15, message: '长度不大于15个字符', trigger: 'blur' },
          { required: true, message: '请输入网络地址', trigger: 'blur' }
        ],
        mask: [
          { max: 15, message: '长度不大于17个字符', trigger: 'blur' },
          { required: true, message: '请输入mac地址', trigger: 'blur' }
        ],
        gateway: [
          { max: 15, message: '长度不大于15个字符', trigger: 'blur' },
          { required: true, message: '请输入网关', trigger: 'blur' }
        ],
        usergroups: [{ required: true, message: '请输入使用群体', trigger: 'blur' }]
      },
      segmentListData: [],
      total: 0,
      ipEditForm: {},
      dialogIpEditFormVisible: false
    }
  },
  created() {
    this.getSegment()
  },
  methods: {
    // 添加网段
    addNetwork() {
      this.$refs.addNetworkFormRef.validate(async (valid) => {
        if (valid === false) return false
        const myDate = new Date()
        const y = myDate.getFullYear()
        const M = myDate.getMonth() + 1
        const d = myDate.getDate()
        const h = myDate.getHours()
        const m = myDate.getMinutes()
        const s = myDate.getSeconds()
        const myDateTime = `${y}-${M}-${d} ${h}:${m}:${s}`
        this.$set(this.addNetworkForm, 'create_time', myDateTime)
        const { data: ressg } = await this.$http.post('/api/ip/segment', this.addNetworkForm)
        if (ressg.code !== 0) return this.$message.error('添加网段失败！')
        this.$message.success('添加网段成功！')
        // 刷新网段
        this.getSegment()
        // 添加ip
        var arrip = []
        var prexip = this.addNetworkForm.segment.split('.')
        prexip.pop()
        for (let i = 1; i < 255; i++) {
          const ip = prexip.join('.') + `.${i}`
          const tempip = { ip: ip, mask: this.addNetworkForm.mask, gateway: this.addNetworkForm.gateway, segment: this.addNetworkForm.segment }
          arrip.push(tempip)
        }
        const { data: resip } = await this.$http.post('api/ip/ip', arrip)
        console.log(resip)
        if (resip.code !== 0) return this.$message.error('添加ip地址失败!')
        this.$message.success('添加ip地址成功!')
      })
    },
    // 重置
    resetForm() {
      this.$refs.addNetworkFormRef.resetFields()
    },
    // 获取网段方法
    async getSegment() {
      const { data: res } = await this.$http.get('api/ip/segment')
      this.segmentListData = res.data
      this.total = res.total
    },
    // 调整每页显示行数事件
    handleSizeChange(size) {
      this.searchIpForm.pagesize = size
      this.getIpList()
    },
    // 翻页事件
    handleCurrentChange(num) {
      this.searchIpForm.pagenum = num
      this.getIpList()
    },
    // 授权
    editIp(row) {
      this.dialogIpEditFormVisible = true
      this.ipEditForm = JSON.parse(JSON.stringify(row))
    },
    async editSaveIp() {
      const myDate = new Date()
      const y = myDate.getFullYear()
      const M = myDate.getMonth() + 1
      const d = myDate.getDate()
      const h = myDate.getHours()
      const m = myDate.getMinutes()
      const s = myDate.getSeconds()
      const myDateTime = `${y}-${M}-${d} ${h}:${m}:${s}`
      this.$set(this.ipEditForm, 'create_time', myDateTime)
      console.log(this.ipEditForm)
      const { data: res } = await this.$http.put(`/api/ip/${this.ipEditForm.id}`, this.ipEditForm)
      if (res.code !== 0) return this.$message.error('保存失败！')
      this.$message.success('保存成功！')
      this.dialogIpEditFormVisible = false
      this.getIpList()
    },
    // 删除
    async deleteSeg(scope) {
      console.log(scope)
      const { data: res } = await this.$http.delete(`/api/ip/segment/${scope.row.id}`)
      if (res.code !== 0) return this.$message.error('删除失败！')
      this.$message.success('删除成功！')
      scope._self.$refs[`popover-${scope.$index}`].doClose()
      this.getSegment()
    },
    // 取消操作
    cancelAction(scope) {
      scope._self.$refs[`popover-${scope.$index}`].doClose()
    }
  }
}
</script>

<style lang="less" scoped>
.tableRowButton {
  margin-right: 5px;
}
</style>
